import React, {useEffect, useRef} from "react";
import {createStyles} from "antd-style";
import {useBgContainerIndexStore} from "@/store/BaseStore.ts";

// 图片渐变的时间
const imageLoadingTime = 3000
// 图片修改的时间
// const changeImageTime = 20000
const changeImageTime = 5000

const baseLink = "/api/photo"
let imgLink = ""

const useStyle = createStyles(({css, token}) => {
    return {
        container: css`
          width: 100%;
          height: 100%;
          position: fixed;
          left: 0;
          top: 0;
          z-index: -3;
          
          @keyframes littleMove {
            0% {
              width: 100%;
              height: 100%;
              //transform: scale(1);
            }
            100% {
              width: 110%;
              height: 110%;
              //transform: scale(1.2);
            }
          }
          
          img {
            position: absolute;
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center;
            transition: opacity ${imageLoadingTime}ms ease-out, 
                        filter ${imageLoadingTime}ms ease-out,
                        transform ${imageLoadingTime}ms ease-out;
            opacity: 1;
            filter: blur(0) brightness(100%);
            animation:  littleMove ${changeImageTime * 1.5}ms linear ${imageLoadingTime}ms 1 forwards ;
          }
          
          .front {
            z-index: -10;
          }

          .backend {
            z-index: -20;
          }
          
          .fadeOut {
            opacity: 0;
            transform: scale(1.5);
            filter: blur(30px) brightness(150%);
          }
        `
    }
})

interface PropType {
    pause?: boolean
}

const removeFadeOut = (target: HTMLImageElement) => {
    target.classList.remove("fadeOut")
}

const setFadeOut = (target: HTMLImageElement) => {
    target.classList.add("fadeOut")
}

const setBackImage = (target: HTMLImageElement) => {
    target.classList.remove("front")
    target.classList.add("backend")
}

const setFrontImage = (target: HTMLImageElement) => {
    target.classList.remove("backend")
    target.classList.add("front")
}

interface CustomImage {
    image: HTMLImageElement,
    destroyed: boolean,
    destroy: Function,
    setFront: Function
}

const getImage = (src: string): CustomImage => {
    const image = new Image();
    setBackImage(image)
    image.src = src;
    const customImage: CustomImage = {
        image,
        destroyed: false,
        destroy: (finishedTrigger?: Function) => {
            setFadeOut(image)
            setTimeout(() => {
                image.remove()
                customImage.destroyed = true
                finishedTrigger != null ? finishedTrigger() : null;
            }, imageLoadingTime)
        },
        setFront: () => {
            setFrontImage(image)
        }
    }
    return customImage
}

let paused = false;

/**
 * 图片循环函数
 * @param container div容器对象
 */
const init = (container: HTMLDivElement): Function => {
    let destroy = false
    let first = true
    const _init = (container: HTMLDivElement) => {
        if (destroy) {
            return null
        }
        const image1 = getImage(imgLink + "?t=" + Math.random())
        if (first) {
            setFadeOut(image1.image)
        }
        container.appendChild(image1.image)
        image1.image.addEventListener("load", () => {
            if (first) {
                removeFadeOut(image1.image)
                first = false
            }
            setTimeout(() => {
                image1.setFront()
                if (paused === true) {
                    return
                }
                const image2 = _init(container);
                if (image2 != null) {
                    image2.image.addEventListener("load", () => {
                        setTimeout(() => {
                            image1.destroy()
                        }, 1000)
                    })
                }
            }, changeImageTime - 1000)
        })
        return image1
    }

    _init(container)
    return () => {
        container.innerHTML = ""
        destroy = true
    }
}

/**
 * 随机背景图片
 * @param pause 传入true值时停止背景切换
 */
const BackgroundImage: React.FC<PropType> = ({pause}) => {
    const {styles} = useStyle();
    const container = useRef(null);
    const index = useBgContainerIndexStore(state => state.index);
    if (index != null && index != -1) {
        imgLink = baseLink + "/" + index;
    } else {
        imgLink = baseLink
    }
    paused = pause === true

    useEffect(() => {
        const destroyTrigger = init(container.current)
        return () => {
            destroyTrigger()
        }
    }, [pause]);

    return (
        <div className={styles.container} ref={container}>

        </div>
    )
}

export default BackgroundImage;
